<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input
          v-model="queryParams.roleKey"
          placeholder="请输入权限字符"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:del']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:del']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色ID" prop="id"/>
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true"/>
      <el-table-column prop="dataScope" label="数据权限" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_data_scope" :value="scope.row.dataScope"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:del']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check"
                                v-hasPermi="['system:role:edit']">数据权限</el-dropdown-item>
              <el-dropdown-item command="handleMenu" icon="el-icon-user"
                                v-hasPermi="['system:role:menu']">分配菜单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  分配用户菜单弹窗  -->
    <el-dialog :title="title" :visible.sync="openMenu" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="菜单选项">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMenus">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {listRole, addRole, getRole, updateRole, delRole, getTreeMenus, updateRoleMenus} from "@/api/system/role";
import {parseTime} from "@/utils/nami";

export default {
  name: 'Role',
  dicts: ['sys_def_flag', 'sys_data_scope'],
  data() {
    return {
      // 分配数据权限弹窗
      openDataScope: false,
      // 弹出层开关
      open: false,
      openMenu: false,
      // 弹出层标题
      title: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],
      // 角色表格数据
      roleList: [],
      // 表单参数
      form: {},
      // 菜单列表
      menuOptions: [],
      menuExpand: false,
      menuNodeAll: false,
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      rules:{
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ]
      },
      // 选中数组
      ids: [],
    }
  },
  methods: {
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleMenu":
          this.handleMenu(row);
          break;
        default:
          break;
      }
    },
    /** 分配数据权限 */
    handleDataScope(row) {

    },
    /** 分配菜单提交按钮 */
    submitMenus() {
      if (this.form.id != undefined) {
        this.form.menuIds = this.getMenuAllCheckedKeys();
        updateRoleMenus(this.form).then(resp => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.cancelDataScope();
          this.getList();
        })
      } else {
        this.$modal.msg("数据有误！");
      }
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 提交按钮 */
    submitDataScope() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(this.form.id === undefined) {
            addRole(this.form).then(()=> {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            updateRole(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            })
          }
        }
      })
    },
    /** 取消按钮 */
    cancelDataScope() {
      this.openMenu = false;
      this.reset();
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 删除按钮 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？', '系统提示', {
        confirmButtonText: "确定",//必填
        cancelButtonText: "取消",//必填
        type: "warning",//必填
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "执行中...";
            await delRole(roleIds).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }).catch(() => {})
          }
          instance.confirmButtonLoading = false;
          done();
        }
      }).catch(() => {})
    },
    /** 修改按钮*/
    handleUpdate(row) {
      const id = row.id || this.ids
      this.$modal.loading('查询数据中。。。')
      getRole(id).then(resp => {
        this.reset();
        this.form = resp;
        this.$modal.closeLoading();
        this.open = true;
      }).catch(() => {
        this.$modal.closeLoading();
        this.reset();
      })
    },
    /** 新增角色 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增用户"
    },
    /** 表单重置 */
    reset() {
      this.resetForm("form");
      this.form = {};
      this.ids = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listRole(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.roleList = response.records;
          this.total = parseInt(response.pageResult.totalRecords);
          this.loading = false;
        }
      );
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.form.menuCheckStrictly = value ? true: false;
    },
    // 打开分配菜单的弹窗
    handleMenu(row) {
      this.reset();
      const menuTreeSelect = this.getMeneTree(row.id);
      this.$nextTick(() => {
        menuTreeSelect.then(res => {
          this.$refs.menu.setCheckedKeys(res.ids);
        });
      });
      this.form.id = row.id;
      this.openMenu = true;
      this.title = "分配菜单"
    },
    getMeneTree(id) {
      return getTreeMenus(id).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 文件导出 */
    handleExport() {
      this.download('system/role/export', {
        ...this.queryParams
      }, `角色_${parseTime(new Date())}.xlsx`)
    }
  },
  created() {
    this.getList();
  },
}
</script>

<style scoped>

</style>
